<!-- 小组管理 -->
<template>
  <div>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="任务编号">
        <el-input
          clearable
          size="small"
          v-model="formInline.number"
          auto-complete="off"
          placeholder="请输入任务编号"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="getData">查询</el-button>
        <el-button size="small" type="primary" @click="add()" v-if="userInfo.role == 1">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table
      size="small"
      :data="datalist"
      highlight-current-row
      border
      element-loading-text="拼命加载中"
      style="width: 100%;"
    >
      <el-table-column align="center" sortable prop="number" label="任务编号" min-width="150"></el-table-column>
      <el-table-column align="center" sortable prop="name" label="预按名称" min-width="100"></el-table-column>
      <el-table-column align="center" sortable prop="time" label="救援时间" min-width="100"></el-table-column>
      <el-table-column align="center" sortable prop="level" label="等级" min-width="100"></el-table-column>
      <el-table-column align="center" sortable prop="scale" label="规模" min-width="100"></el-table-column>
      <el-table-column align="center" sortable prop="peopleNum" label="人数" min-width="200"></el-table-column>
      <el-table-column align="center" sortable prop="deviceName" label="设备" min-width="200"></el-table-column>
      <el-table-column align="center" sortable prop="status" label="状态" width="100">
        <template slot-scope="scope">{{ scope.row.status == 1 ? '进行中' : '结束' }}</template>
      </el-table-column>
      <el-table-column align="center" sortable prop="address" label="救援地址" min-width="200"></el-table-column>
      <el-table-column align="center" sortable prop="casualtiesNum" label="伤亡数" width="100"></el-table-column>
      <el-table-column align="center" label="操作" width="150" v-if="userInfo.role == 1">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == 1"
            size="mini"
            type="primary"
            @click="over(scope.row)"
          >结束任务</el-button>
          <el-button
            v-if="scope.row.status == 2"
            size="mini"
            type="primary"
            @click="update(scope.row)"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="page-box"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      background
      :current-page="pageparm.currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageparm.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageparm.total"
    ></el-pagination>
    <el-dialog :title="title" :visible.sync="addVisible" width="70%" @click="closeDialog()">
      <el-form ref="addData" :rules="configRules" :model="addData" label-width="100px">
        <el-row v-show="!isDiasble">
          <el-col :span="8">
            <el-form-item label="导入预按" prop="plan">
              <el-select v-model="addData.plan" placeholder="请选择" @change="changeData" clearable>
                <el-option
                  v-for="item in planList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="任务编号" prop="number">
              <el-input
                size="small"
                v-model="addData.number"
                auto-complete="off"
                placeholder="任务编号"
                :disabled="true"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务名称" prop="name" :disabled="isDiasble">
              <el-input size="small" v-model="addData.name" auto-complete="off" placeholder="任务名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类型" prop="type">
              <el-input size="small" v-model="addData.type" auto-complete="off" placeholder="类型"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="预案等级" prop="level">
              <el-input size="small" v-model="addData.level" auto-complete="off" placeholder="预案等级"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预按规模" prop="scale">
              <el-input size="small" v-model="addData.scale" auto-complete="off" placeholder="预按规模"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="人数" prop="peopleNum">
              <el-input
                size="small"
                v-model="addData.peopleNum"
                auto-complete="off"
                placeholder="人数"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="预案设备" prop="deviceIds">
              <el-cascader
                v-model="addData.deviceIds"
                :options="deviceTypeTree"
                :props="props"
                clearable
                :show-all-levels="false"
              ></el-cascader>
              <!-- <el-select
                v-model="addData.deviceIds"
                multiple
                placeholder="请选择"
                :disabled="isDiasble"
              >
                <el-option
                  v-for="item in devices"
                  :key="item.id"
                  :label="item.deviceName"
                  :value="item.id"
                ></el-option>
              </el-select>-->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地址" prop="address">
              <el-input size="small" v-model="addData.address" auto-complete="off" placeholder="地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="伤亡数" prop="casualtiesNum">
              <el-input
                size="small"
                v-model="addData.casualtiesNum"
                auto-complete="off"
                placeholder="伤亡数"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="!isDiasble">
          <el-col :span="8">
            <el-form-item label="小组" prop="groupName">
              <el-input
                size="small"
                v-model="addData.groupName"
                auto-complete="off"
                :disabled="true"
                width="200px"
              >
                <el-button slot="append" icon="el-icon-search" @click="selectGroup()">智能查询</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        size="small"
        :data="groupList"
        highlight-current-row
        border
        element-loading-text="拼命加载中"
        style="width: 100%;"
        @current-change="handleChange"
        v-show="!isDiasble"
      >
        <el-table-column align="center" sortable prop="groupName" label="小组名称" min-width="150"></el-table-column>
        <el-table-column align="center" sortable prop="lastTime" label="上次出警时间" min-width="100"></el-table-column>
        <el-table-column align="center" sortable prop="dutyCount" label="在岗人数" min-width="100"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog()">取消</el-button>
        <el-button size="small" type="primary" class="title" @click="addGroup()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getAllList } from "../../api/xiaofang/plan";
import { available } from "../../api/xiaofang/device";
import { getTypeTree } from "../../api/xiaofang/deviceType";
import {
  groupList,
  add,
  getList,
  over,
  updateTask
} from "../../api/xiaofang/task";
export default {
  data() {
    return {
      props: { multiple: true },
      addData: {
        number: "",
        groupId: "",
        groupName: ""
      },
      configRules: {
        number: [{ required: true, message: "必填", trigger: "change" }],
        name: [{ required: true, message: "必填", trigger: "change" }],
        deviceIds: [{ required: true, message: "必填", trigger: "change" }],
        groupName: [{ required: true, message: "必填", trigger: "change" }]
      },
      pageparm: {
        currentPage: 0,
        pageSize: 10,
        total: 0
      },
      datalist: [],
      formInline: {},
      title: "",
      addVisible: false,
      devices: [],
      isDiasble: false,
      planList: [],
      groupList: [],
      userInfo: {},
      deviceTypeTree: [],
      deviceTypeList: []
    };
  },
  created() {
    this.getData();
    this.deviceData();
    this.getPlanList();
    this.userInfo = JSON.parse(sessionStorage.getItem("sysuser"));
    this.getTypeTree();
  },
  methods: {
    getTypeTree(param) {
      getTypeTree({ deviceIds: param }).then(res => {
        this.deviceTypeTree = res;
        if (!param) {
          this.deviceTypeList = Object.assign({}, res);
        }
      });
    },

    generateSixDigitNumber() {
      let min = 100000;
      let max = 999999;
      let randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
      return randomNumber.toString();
    },
    over(row) {
      let param = {};
      param.id = row.id;
      over(param).then(res => {
        if (res.status == 200) {
          this.$message.success("结束成功");
          this.getData();
        } else {
          this.$message.error(res.info);
        }
      });
    },
    handleChange(row) {
      this.addData.groupId = row.id;
      this.addData.groupName = row.groupName;
      this.$forceUpdate();
    },
    selectGroup() {
      if (this.addData.peopleNum == "" || this.addData.peopleNum == null) {
        this.$message.error("请先填写人数");
        return;
      }
      let arr = [];
      this.addData.deviceIds.forEach(deviceId => {
        arr.push(deviceId[1]);
      });
      Object.assign(this.addData.deviceIds, arr);
      groupList(this.addData).then(res => {
        if (res.status == 200) {
          this.groupList = res.data;
          if (this.groupList != null && this.groupList.length > 0) {
            this.addData.groupId = this.groupList[0].id;
            this.addData.groupName = this.groupList[0].groupName;
            this.$forceUpdate();
          }
        } else {
          this.$message.error(res.info);
        }
      });
    },
    changeData(value) {
      let param = {};
      if (value == "") {
        this.addData = {
          type: null,
          address: null,
          deviceIds: null,
          peopleNum: null,
          scale: null,
          level: null,
          deviceIds: null,
          number: this.addData.number
        };
      } else {
        this.planList.forEach(element => {
          if (element.id == value) {
            this.addData.type = element.type;
            this.addData.address = element.address;
            // this.addData.deviceIds = value.deviceIds.map(str => parseInt(str, 10));
            this.addData.peopleNum = element.numPeople;
            this.addData.scale = element.scale;
            this.addData.level = element.level;
            (this.addData.deviceIds = null), (param = element);

            let date = new Date();
            let isoString = date.toISOString();
            let formattedTime = isoString.substring(0, 19).replace("T", " ");
            console.log(formattedTime);
            this.addData.name = formattedTime + "-" + element.name;
          }
        });
        // this.addData.type = value.type;
        // this.addData.address = value.address;
        // // this.addData.deviceIds = value.deviceIds.map(str => parseInt(str, 10));
        // this.addData.peopleNum = value.numPeople;
        // this.addData.scale = value.scale;
        // this.addData.level = value.level;
      }
      this.getTypeTree(param.deviceTypes);
      // if (value.type != "" && value.type != null) {
      //   this.addData.type = value.type;
      // }
      // if (value.address != "" && value.address != null) {
      //   this.addData.address = value.address;
      // }
      // if (value.deviceIds) {
      //   this.addData.deviceIds = value.deviceIds.map(str => parseInt(str, 10));
      // }
      // if (value.numPeople != "" && value.numPeople != null) {
      //   this.addData.peopleNum = value.numPeople;
      // }

      // if (value.scale != "" && value.scale != null) {
      //   this.addData.scale = value.scale;
      // }

      // if (value.level != "" && value.level != null) {
      //   this.addData.level = value.level;
      // }
    },
    getPlanList() {
      getAllList().then(res => {
        this.planList = res;
      });
    },
    deviceData() {
      available().then(res => {
        this.devices = res;
      });
    },
    del(row) {
      deletePlan(row.id).then(res => {
        if (res.status == 200) {
          this.$message.success("删除成功");
          this.getData();
        } else {
          this.$message.error(res.info);
        }
      });
    },
    update(row) {
      this.isDiasble = true;
      this.addData = row;
      this.addData.deviceIds = this.addData.deviceIds.map(str =>
        parseInt(str, 10)
      );
      this.addVisible = true;
      this.title = "修改任务";
    },
    addGroup() {
      this.$refs.addData.validate(valid => {
        if (valid) {
          if (this.addData.id) {
            updateTask(this.addData).then(res => {
              if (res.status == 200) {
                this.$message.success("修改成功");
                this.addVisible = false;
                this.getData();
              } else {
                this.$message.error(res.info);
              }
            });
          } else {
            add(this.addData).then(res => {
              if (res.status == 200) {
                this.$message.success("保存成功");
                this.addVisible = false;
                this.getData();
              } else {
                this.$message.error(res.info);
              }
            });
          }
        }
      });
    },
    closeDialog() {
      this.addVisible = false;
    },
    add() {
      this.isDiasble = false;
      this.addData = {};
      this.addVisible = true;
      this.title = "新增任务";
      this.groupList = [];
      this.addData.number = this.generateSixDigitNumber();
    },
    handleCurrentChange(val) {
      this.pageparm.currentPage = val;
      this.getData();
    },
    handleSizeChange(val) {
      this.pageparm.pageSize = val;
      this.getData();
    },
    getData() {
      this.formInline.pageIndex = this.pageparm.currentPage;
      this.formInline.pageSize = this.pageparm.pageSize;
      getList(this.formInline).then(res => {
        this.datalist = res.records;
        this.pageparm.total = res.total;
      });
    }
  }
};
</script>